//
//  UIImage+YTAdd.m
//  tesDemo02
//
//  Created by 拓客营 on 2022/3/21.
//

#import "UIImage+YTAdd.h"

@implementation UIImage (YTAdd)

- (UIImage *)resizeByDefaultInset{
    CGSize size = self.size;
    UIEdgeInsets insets = UIEdgeInsetsMake(size.height/2 - 1, size.width/2-1, size.height/2, size.width/2);
    UIImage *image = self.copy;
    image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    return image;
}


+ (UIImage *)redrawImage:(UIImage *)image withText:(NSString *)text{
    return [self redrawImage:image withText:text attributes:nil];
}

+ (UIImage *)redrawImage:(UIImage *)image withText:(NSString *)text attributes:(NSDictionary<NSString *,id> *)attributes{
    
    if (!text || text.length == 0) {
        return nil;
    }
    
    if (!attributes) {
        attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12.f], NSForegroundColorAttributeName:[UIColor whiteColor]};
    }
    
    CGSize textSize = [text sizeWithAttributes:attributes];
    
    if (textSize.width > image.size.width) {
        textSize.width = image.size.width;
    }
    
    if (textSize.height > image.size.height) {
        textSize.height = image.size.height;
    }
    
    CGPoint startPoint = CGPointMake(image.size.width / 2 - textSize.width/2, image.size.height/2 - textSize.height/2 - 2.f);
    
    
    
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    [text drawAtPoint:startPoint withAttributes:attributes];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

- (UIImage *)imageByAddWithColor:(UIColor *)color lineWeight:(CGFloat)lineWeight{
    
    UIImage *image = [UIImage imageWithColor:color size:CGSizeMake(self.size.width, lineWeight)];
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    
    [image drawInRect:CGRectMake(0, self.size.height-lineWeight, self.size.width, lineWeight)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}


- (UIImage *)cutForAvatar{
    
    /**
     
     根据图片原的长宽高(image.size)，获取短的那边；
     然后将图片重绘到该区域，选择contentMode为UIViewContentModeScaleAspectFill（填充）模式；
     这样会得到一个方形的图片(之所以选择UIViewContentModeScaleAspectFill这个模式，是因为ImageView的contentMode如果为该值得话，会将图片显示完整，即使超过imageView的size，可以去试试。将ImageView的clipsToBounds设置为YES就可以去掉多余的显示内容)
     在将图片切成圆角
     
     PS:理论上这里的圆角图片应该进行一次缓存  这样不用每次都去做这些操作  后期想办法优化吧~
     
     */
    
    CGFloat cutWidth = self.size.width > self.size.height ? self.size.height : self.size.width;
    
    UIImage *newImage = [self imageByResizeToSize:CGSizeMake(cutWidth, cutWidth) contentMode:UIViewContentModeScaleAspectFill];
    newImage = [newImage imageByRoundCornerRadius:cutWidth/2
                                      borderWidth:CGFloatFromPixel(1.f)
                                      borderColor:[UIColor colorWithRGB:0xe8e8e8]];
    
    return newImage;
}


+ (UIImage *)buttonBackgroundImageWithColor:(UIColor *)color corner:(CGFloat)corner{
    UIImage *image = [UIImage imageWithColor:color size:CGSizeMake(10, 10)];
    image = [image imageByRoundCornerRadius:corner];
    image = [image resizeByDefaultInset];
    return image;
}

- (UIImage *)imageRedrawWithColor:(UIColor *)color {
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //翻转
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    CGContextClipToMask(context, rect, self.CGImage);
    
    [color setFill];
    
    CGContextFillRect(context, rect);
    
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

//压缩图片 size 单位 M
- (UIImage *)compressWithMaxLength:(CGFloat)maxLength{
    maxLength = maxLength * 1024;//M转换成KB
    // 压缩质量
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    //压缩质量之前,图像大小 = %ld KB",data.length/1024;
    if (data.length <= maxLength) {
        
//        UIImage *newImage = [UIImage imageWithData:data scale:1.0];
//        return newImage;
        return self;
    }
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(self, compression);
        //压缩 = %.1f", compression);
        //在压缩质量循环,图像大小 = %ld KB", data.length / 1024);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //压缩质量后,图像大小 = %ld KB", data.length / 1024);
    UIImage *resultImage = [UIImage imageWithData:data];
    
//    // 通过改变图片尺寸来压缩
//    NSUInteger lastDataLength = 0;
//    while (data.length > maxLength && data.length != lastDataLength) {
//        lastDataLength = data.length;
//        CGFloat ratio = (CGFloat)maxLength / data.length;
//
//        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
//                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); //使用了NSUInteger防止白色空白
//        UIGraphicsBeginImageContext(size);
//        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
//        resultImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//        data = UIImageJPEGRepresentation(resultImage, compression);
//        //循环压缩大小,图像大小 = %ld KB", data.length / 1024);
//    }
//    data = UIImageJPEGRepresentation(self, compression);
//    //循环压缩大小后的图像
    
    return resultImage;
}


/**
 *  生成二维码
 */
+ (UIImage *)creatCIQRCodeImage:(NSString *)dataStr withSize:(CGFloat)size{
    //创建过滤器，这里的@"CIQRCodeGenerator"是固定的
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //恢复默认设置
    [filter setDefaults];
    //给过滤器添加数据
    NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    //value必须是NSData类型
    [filter setValue:data forKeyPath:@"inputMessage"];
    //生成二维码
    CIImage *outputImage = [filter outputImage];
    //显示二维码
    return [self creatNonInterpolatedUIImageFormCIImage:outputImage withSize:size];
}

+ (UIImage *)creatNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    //创建bitmap
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    //保存bitmap图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

+ (UIImage *)convertCreateImageWithUIView:(UIView *)view{

    // 设置绘制图片的大小
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    // 绘制图片
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
       
    return image;
}

+ (UIImage*) convertImageToGreyScale:(UIImage*) image{
    // Create image rectangle with current image width/height
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    
    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    
    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    
    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, imageRect, [image CGImage]);
    
    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    
    // Create a new UIImage object
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    
    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    
    // Return the new grayscale image
    return newImage;
}

@end
